package com.platform.spring_security.filter;


import com.platform.common_utils.R;
import com.platform.common_utils.ResponseUtil;
import com.platform.spring_security.entity.SecurityUser;
import com.platform.spring_security.security.TokenManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * <p>
 *  登陆过滤器
 * </p>
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;

    public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
        this.setPostOnly(false);
        //如果请求是/admin/user/login路径的，过滤器就进行过滤，调用相应方法看用户名密码是否正确，不会调到自己写的controller，由springsecurity自动认证用户名密码
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/acl/user/login","POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException {
        try {
            //从登录请求中过滤中User
            //User user = new ObjectMapper().readValue(req.getInputStream(), User.class);
            System.out.println("登录过滤器:");
            System.out.println("被过滤的url为："+req.getRequestURI());
            System.out.println();
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            System.out.println(username);

                                                            //UsernamePasswordAuthenticationToken：根据请求的user验证用户名和密码（这个类会自动验证）
                                                            //请求中的密码在校验时会被 DefaultPasswordEncoder 加密后校验，所以直接传账号密码就能进行校验
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password, new ArrayList<>()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 登录成功
     * @param req
     * @param res
     * @param chain
     * @param auth
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {
        SecurityUser user = (SecurityUser) auth.getPrincipal();
        String token = tokenManager.createToken(user.getCurrentUserInfo().getUsername());
        System.out.println("登陆成功！");
        //通过用户名生成token
        //往redis中存入当前用户的权限列表（key：username value：该用户的权限列表）
        redisTemplate.opsForValue().set(user.getCurrentUserInfo().getUsername(), user.getPermissionValueList());
        //返回token
        ResponseUtil.out(res, R.ok().data("token", token).message("登录认证成功，返回token"));
    }

    /**
     * 登录失败
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              AuthenticationException e) throws IOException, ServletException {
        ResponseUtil.out(response, R.error().message("登录失败！用户名密码或错误"));
    }
}
